﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using FaceSharp.Api.GraphApi;
using Newtonsoft.Json.Linq;
using Types = FaceSharp.Api.Types;

namespace FaceSharp.Api.Objects
{
    public class Photo : GraphBase
    {
        private readonly IFacebookCore _facebookCore;
        public Photo(IFacebookCore facebookCore)
            : base(facebookCore)
        {
            _facebookCore = facebookCore;
        }
        public Types.Photo Get(string photoId)
        {
            Trace.Write("Begin Request :" + photoId, "GraphApi.GetPhoto");
            var jObject = MakeGraphRequest(photoId);
            var photo = new Types.Photo();
            if (jObject != null)
            {
                photo = jObject.ToObject<Types.Photo>();
            }
            Trace.Write("End Request", "GraphApi.GetPhoto");
            return photo;
        }

        /// <summary>
        /// Uploads a photo to the specified photo album.
        /// </summary>
        /// <param name="albumId"></param>
        /// <param name="message"></param>
        /// <param name="photo"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public string Add(string albumId, string message, Image photo, System.Drawing.Imaging.ImageFormat format)
        {
            Trace.Write("Begin Request", "GraphApi.UploadPhoto");
            var client = new RestSharp.RestClient("https://graph.facebook.com/");
            var request = new RestSharp.RestRequest(albumId + "/photos", RestSharp.Method.POST);
            request.AddParameter("access_token", _facebookCore.AccessToken);
            request.AddParameter("message", message);

            var ms = new MemoryStream();
            photo.Save(ms, format);
            ms.Position = 0;
            
            request.AddFile("photo",ms.ToArray(),"image." + format.ToString().ToLower());

            var response = client.Execute(request);

            ms.Close();
            ms.Dispose();
            

            var returnValue = string.Empty;
            if (response.StatusCode != HttpStatusCode.OK)
            {
                Trace.TraceWarning(response.Content);
            }
            else
            {
                var jObject = JObject.Parse(response.Content);
                returnValue = jObject["id"].ToString();
            }
            Trace.Write("End Request", "GraphApi.UploadPhoto");
            return returnValue;
        }
    }
}